<template>
  <div>
    <template v-if="selectModel">
      <el-tree
        ref="tree"
        :data="treeList"
        show-checkbox
        node-key="id"
        @check="getCurrentNode"
        :default-checked-keys="selectModelKeysNew"
        :props="treeProps"
      >
      </el-tree>
    </template>
    <template v-else>
      <div class="divBox">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-button
              size="mini"
              type="primary"
              v-if="checkPermi(['platform:product:category:add'])"
              @click="handleAddMenu({ id: 0, name: $t('dingCengMuLu') })"
              >{{ $t('xinZeng') }}{{ biztype.name }}</el-button
            >
            <el-button
              size="mini"
              type="primary"
              @click="syncFn"
              v-if="checkPermi(['platform:product:category:sync'])"
              >{{ $t('tongBu') }}</el-button
            >
          </div>
          <el-table
            :data="dataList"
            size="mini"
            v-loading="listLoading"
            class="table"
            highlight-current-row
            row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column prop="name" :label="$t('mingCheng')" min-width="200">
              <template slot-scope="scope"> {{ scope.row.name }} | {{ scope.row.id }} </template>
            </el-table-column>
            <template v-if="!selectModel">
              <el-table-column :label="$t('jiBie')" min-width="150">
                <template slot-scope="scope">
                  <span>{{ scope.row.level }}</span>
                  <!--<span>{{ scope.row.type | filterCategroyType | filterEmpty }}</span>-->
                </template>
              </el-table-column>
              <el-table-column :label="$t('fenLeiTuBiao')" min-width="80">
                <template slot-scope="scope">
                  <div class="demo-image__preview">
                    <el-image
                      style="width: 36px; height: 36px"
                      :src="scope.row.icon"
                      :preview-src-list="[scope.row.icon]"
                      v-if="scope.row.icon"
                    />
                    <img style="width: 36px; height: 36px" v-else :src="defaultImg" alt="" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('paiXu')" prop="sort" min-width="150" />
              <el-table-column :label="$t('zhuangTai')" min-width="150">
                <!--  -->
                <template slot-scope="scope" v-if="checkPermi(['admin:category:update:status'])">
                  <el-switch
                    v-model="scope.row.isShow"
                    :active-value="true"
                    :inactive-value="false"
                    :active-text="$t('xianShi')"
                    :inactive-text="$t('yinCang')"
                    @change="onchangeIsShow(scope.row)"
                  />
                </template>
              </el-table-column>

              <el-table-column :label="$t('caoZuo')" min-width="200" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    v-if="scope.row.level < 3 && checkPermi(['platform:product:category:add'])"
                    @click="handleAddMenu(scope.row)"
                    >{{ $t('tianJiaZiMuLu') }}</el-button
                  >
                  <el-button
                    type="text"
                    v-if="checkPermi(['platform:product:category:update'])"
                    size="small"
                    @click="handleEditMenu(scope.row)"
                    >{{ $t('bianJi') }}</el-button
                  >
                  <el-button
                    type="text"
                    v-if="checkPermi(['platform:product:category:delete'])"
                    size="small"
                    @click="handleDelMenu(scope.row)"
                    >{{ $t('shanChu') }}</el-button
                  >
                </template>
              </el-table-column>
            </template>
          </el-table>
        </el-card>
      </div>
    </template>
    <el-dialog
      :title="editDialogConfig.isCreate === 0 ? `${$t('chuangJian')}${biztype.name}` : `${$t('bianJi')}${biztype.name}`"
      :visible.sync="editDialogConfig.visible"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <edit
        v-if="editDialogConfig.visible"
        :prent="editDialogConfig.prent"
        :is-create="editDialogConfig.isCreate"
        :edit-data="editDialogConfig.data"
        :biztype="editDialogConfig.biztype"
        :all-tree-list="dataList"
        @hideEditDialog="hideEditDialog"
      />
    </el-dialog>
  </div>
</template>

<script>
import * as categoryApi from '@/api/categoryApi.js';
import * as storeApi from '@/api/store.js';
import info from './info';
import edit from './edit';
import * as selfUtil from '@/utils/ZBKJIutil.js';
import { checkPermi, checkRole } from '@/utils/permission';
export default {
  // name: "list"
  components: { info, edit },
  props: {
    biztype: {
      // 类型，1 产品分类，2 附件分类，3 文章分类， 4 设置分类， 5 菜单分类
      type: Object,
      default: { value: -1 },
      validator: (obj) => {
        return obj.value > 0;
      },
    },
    pid: {
      type: Number,
      default: 0,
      validator: (value) => {
        return value >= 0;
      },
    },
    selectModel: {
      // 是否选择模式
      type: Boolean,
      default: false,
    },
    selectModelKeys: {
      type: Array,
    },
    rowSelect: {},
  },
  data() {
    return {
      listLoading: false,
      selectModelKeysNew: this.selectModelKeys,
      loading: false,
      constants: this.$constants,
      treeProps: {
        label: 'name',
        children: 'child',
        // expandTrigger: 'hover',
        // checkStrictly: false,
        // emitPath: false
      },
      // treeCheckedKeys:[],// 选择模式下的属性结构默认选中
      multipleSelection: [],
      editDialogConfig: {
        visible: false,
        isCreate: 0, // 0=创建，1=编辑
        prent: {}, // 父级对象
        data: {},
        biztype: this.biztype, // 统一主业务中的目录类型
      },
      dataList: [],
      treeList: [],
      listPram: {
        pid: this.pid,
        type: this.biztype.value,
        isShow: -1,
        name: '',
        page: this.$constants.page.page,
        limit: this.$constants.page.limit[0],
      },
      viewInfoConfig: {
        data: null,
        visible: false,
      },
      defaultImg: require('@/assets/imgs/moren.jpg'),
    };
  },
  mounted() {
    this.handlerGetTreeList();
  },
  methods: {
    checkPermi, //权限控制
    onchangeIsShow(row) {
      storeApi
        .productCategoryShowApi(row.id)
        .then(() => {
          this.$message.success(this.$t('xiuGaiChengGong'));
          this.$store.commit('product/SET_AdminProductClassify', []);
          this.handlerGetTreeList();
        })
        .catch(() => {
          row.isShow = !row.isShow;
        });
    },
    handleEditMenu(rowData) {
      this.editDialogConfig.isCreate = 1;
      this.editDialogConfig.data = rowData;
      this.editDialogConfig.prent = rowData;
      this.editDialogConfig.visible = true;
    },
    handleAddMenu(rowData) {
      this.editDialogConfig.isCreate = 0;
      this.editDialogConfig.prent = rowData;
      this.editDialogConfig.data = {};
      this.editDialogConfig.biztype = this.biztype;
      this.editDialogConfig.visible = true;
    },
    getCurrentNode(data) {
      let node = this.$refs.tree.getNode(data);
      this.childNodes(node);
      // this.parentNodes(node);
      //是否编辑的表示
      // this.ruleForm.isEditorFlag = true;
      //编辑时候使用
      this.$emit('rulesSelect', this.$refs.tree.getCheckedKeys());
      // this.selectModelKeys = this.$refs.tree.getCheckedKeys();
      //无论编辑和新增点击了就传到后台这个值
      // this.$emit('rulesSelect', this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()));
      // this.ruleForm.menuIdsisEditor = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
    },
    //具体方法可以看element官网api
    childNodes(node) {
      let len = node.childNodes.length;
      for (let i = 0; i < len; i++) {
        node.childNodes[i].checked = node.checked;
        this.childNodes(node.childNodes[i]);
      }
    },
    parentNodes(node) {
      if (node.parent) {
        for (let key in node) {
          if (key == 'parent') {
            node[key].checked = true;
            this.parentNodes(node[key]);
          }
        }
      }
    },
    handleDelMenu(rowData) {
      this.$modalSure(this.$t('shanChuDangQianShuJu')).then(() => {
        storeApi.productCategoryDeleteApi(rowData.id).then((res) => {
          this.handlerGetTreeList();
          this.$store.commit('product/SET_AdminProductClassify', []);
          this.$message.success(this.$t('shanChuChengGong'));
        });
      });
    },
    handlerGetList() {
      this.handlerGetTreeList();
    },
    getTree() {
      storeApi.productCategoryApi().then((res) => {
        this.treeList = this.changeNodes(res);
      });
    },
    changeNodes(data) {
      if (data.length > 0) {
        for (var i = 0; i < data.length; i++) {
          if (!data[i].childList || data[i].childList.length < 1) {
            data[i].childList = undefined;
          } else {
            this.changeNodes(data[i].childList);
          }
        }
      }
      return data;
    },
    handlerGetTreeList() {
      storeApi
        .productCategoryListApi()
        .then((res) => {
          console.log(res);
          let obj = {},
            dataList = [];
          res.forEach((item) => {
            obj = item;
            obj.parentId = item.pid;
            obj.children = [];
            dataList.push(obj);
          });
          this.dataList = this.handleTree(dataList, 'menuId');
          console.log(this.dataList);
          this.treeList = this.handleAddArrt(res);
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handlerGetInfo(id) {
      this.viewInfoConfig.data = id;
      this.viewInfoConfig.visible = true;
    },
    handleNodeClick(data) {
      console.log('data:', data);
    },
    handleAddArrt(treeData) {
      const _result = selfUtil.addTreeListLabel(treeData);
      return _result;
    },
    hideEditDialog() {
      setTimeout(() => {
        this.editDialogConfig.prent = {};
        this.editDialogConfig.type = 0;
        this.editDialogConfig.visible = false;
        this.handlerGetTreeList();
      }, 200);
    },
    handleSelectionChange(d1, { checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }) {
      // this.multipleSelection =  checkedKeys.concat(halfCheckedKeys)
      this.multipleSelection = checkedKeys;
      this.$emit('rulesSelect', this.multipleSelection);
    },
    syncFn() {
      storeApi.syncOmsApi().then(() => {
        this.handlerGetTreeList();
        this.$message.success(this.$t('caoZuoChengGong'));
      });
    },
  },
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
